package com.redxiii.spike.engine.commands;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.redxiii.spike.api.command.CommandParameters;
import com.redxiii.spike.api.command.CommandPattern;
import com.redxiii.spike.api.communication.CommunicationService.DefaultMsgs;
import com.redxiii.spike.api.message.Message;
import com.redxiii.spike.api.message.MessageHandler;
import com.redxiii.spike.engine.CoreSettings;
import com.redxiii.spike.util.command.AbstractCommand;
import com.redxiii.spike.util.core.EngineSession;
import com.redxiii.spike.util.core.StorageSystem;

/**
 * @author Daniel Filgueiras
 * @since 19/06/2011
 */
@CommandPattern(patterns={"^//Start ([\\@\\w\\r\\.]+)"})
@CommandParameters(names={"class"})
public class StartHandler extends AbstractCommand {

	private static final Logger logger = LoggerFactory.getLogger(StartHandler.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean proccess(Message message) {

		String classRef = this.getParsedParameter("class");
		Class<MessageHandler> handlerClass;
		
		CoreSettings settings = StorageSystem.getInstance().load(CoreSettings.class);
		
		Map<String,Class<?>> handlerAlias = settings.getHandlerAlias();
		
		try {
			if (handlerAlias.containsKey(classRef)) {
				handlerClass = (Class<MessageHandler>) handlerAlias.get(classRef);
			} else {
				handlerClass = (Class<MessageHandler>) Class.forName(classRef);
			}
			EngineSession.getEngine().addMessageHandler(handlerClass);
			
			service.reply(message, DefaultMsgs.Accepted);
			
			return true;
		} catch(ClassCastException e) {
			service.reply(message, "This is not a MessageHandler");
			logger.warn("Class {} not a MessageHandler class", classRef, e);
			return true;
		} catch(ClassNotFoundException e) {
			service.reply(message, "This handler class / alias was not found");
			logger.warn("Class {} was not found", classRef, e);
			return true;
		} catch(Exception e) {
			logger.error("Error starting handler",e);
		}
		return false;
	}

}
